//
//  MusicDetailViewController.m
//  享动
//
//  Created by darker on 16/4/9.
//  Copyright © 2016年 HHUI. All rights reserved.
//

#import "MusicDetailViewController.h"
#import "MusicDetailTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "MusicPlayViewController.h"
#import "musicListModel.h"
#import <MJRefresh.h>
#import <FMDatabase.h>
#import "AppDelegate.h"
#import "Entity+CoreDataProperties.h"
#import "Entity.h"
#import "one.h"
@interface MusicDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSManagedObjectContext * context;

@property(nonatomic, strong)NSMutableArray * modelArray;
@property(nonatomic, strong)NSMutableArray *iconArray;

@property (weak, nonatomic) IBOutlet UILabel *typeLabel;

@property (weak, nonatomic) IBOutlet UILabel *speed;
@property (weak, nonatomic) IBOutlet UILabel *tempLabel;
@property(nonatomic,assign)NSInteger startIndex;

@property (weak, nonatomic) IBOutlet UIView *bigView;
@property(nonatomic,strong)NSMutableArray * anotherArr;

@property(nonatomic,strong)FMDatabase * db;

@property(nonatomic,strong)NSIndexPath * indexA;
// 正在加载
@property (nonatomic, strong) UIActivityIndicatorView *activity;
// 没有网络的提示框
@property (nonatomic, strong)  UIView *hint;
@end

@implementation MusicDetailViewController

- (void)getByUrl:(NSString *)url
{

    NSDictionary * dic = @{@"index":@"0"};
    _iconArray = [NSMutableArray array];
    [RequestManager requestWithUrl:url requestType:RequestTypePost parDic:dic finish:^(NSData *data) {
        NSDictionary * allDic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * resultArray  = allDic[@"page"][@"result"];
        
        
        for (NSDictionary * one in resultArray) {
            
            musicRunModel * model = [[musicRunModel alloc]init];
            
            [model setValuesForKeysWithDictionary:one];

            [_modelArray addObject:model];

            [_iconArray addObject:model.albumUrl];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
           
            
            musicRunModel * model = _modelArray[0];
            [self.iconView sd_setImageWithURL:[NSURL URLWithString:model.albumUrl]];
            self.typeLabel.text = self.typeString;
            self.tempLabel.text = [NSString stringWithFormat:@"节拍:%ld",model.bpm];
            self.speed.text = model.author;
            
             [self.tableView reloadData];
            [_activity stopAnimating];

        });
    } error:^(NSError *error) {
        NSLog(@"错误");
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
     self.navigationController.navigationBarHidden = YES;
    
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)loadMore
{
    _startIndex += 1;

    _anotherArr = [NSMutableArray array];
    
    
    NSDictionary * dic = @{@"index":[NSString stringWithFormat:@"%ld",_startIndex]};
    
    [RequestManager requestWithUrl:_urlString requestType:RequestTypePost parDic:dic finish:^(NSData *data) {
        NSDictionary * allDic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * resultArray  = allDic[@"page"][@"result"];
        
        
        for (NSDictionary * one in resultArray) {
            musicRunModel * model = [[musicRunModel alloc]init];
            [model setValuesForKeysWithDictionary:one];
            [_anotherArr addObject:model];
            [_iconArray addObject:model.albumUrl];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.modelArray addObjectsFromArray:_anotherArr];
            
            [self.tableView reloadData];
            
        });
        
    } error:^(NSError *error) {
        NSLog(@"错误");
    }];

}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    AppDelegate * delegate = [UIApplication sharedApplication].delegate;
    
    _context = delegate.managedObjectContext;
    
    
    
    
    self.view.frame = CGRectMake(0, 0, KWIDTH, KHEIGHT);
    
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [_activity setCenter:CGPointMake(KWIDTH / 2, KHEIGHT / 2)];
    [_activity startAnimating];
    [self.view addSubview:_activity];
    
    self.tableView.delegate = self;
    
    self.tableView.dataSource =self;
    
    [self.tableView registerClass:[MusicDetailTableViewCell class] forCellReuseIdentifier:@"cell"];

    _modelArray  = [NSMutableArray array];
    
    // 前面七个就解析  后面的就从数据库取
    // 判断有没有网络
    if ([[NetWorkState shareInstance]reachability]) {

   
    if (_index < 7) {
         [self getByUrl:_urlString];
    }
    else
    {
        [_activity stopAnimating];
        musicListModel * model = _musicListArray[_index-7];
        
        _iconView.image = [UIImage imageWithData:model.iconViewData];
        _typeLabel.text = model.listName;
        _speed.text = model.introduce;
        
        
        // 取值
        NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"chooseMusic.db"];

        _db = [FMDatabase databaseWithPath:path];
        [_db open];
        
        FMResultSet * rr = [_db executeQuery:@"SELECT * FROM chooseMusic"];
        
        
        while ([rr next]) {
            BOOL ishave = NO;
        musicRunModel * model = [[musicRunModel alloc]init];
            
          
            
            model.tableName = [rr stringForColumn:@"tableName"];
            model.albumUrl = [rr stringForColumn:@"albumUrl"];
            model.author = [rr stringForColumn:@"author"];
            model.name = [rr stringForColumn:@"name"];
            model.introduce = [rr stringForColumn:@"introduce"];
            model.url = [rr stringForColumn:@"url"];
            model.bpm = [rr intForColumn:@"bpm"];
            
            
            // 判断是否有重复添加的歌曲
            if (_modelArray.count !=0) {
                for (int i = 0; i < _modelArray.count; i++) {
                    if ([model.name isEqualToString:[_modelArray[i] name]]) {
                        ishave = YES;
                    }
                }
            }
            
            
            if ([model.tableName isEqualToString:_tableName] && !ishave) {
  
                [_modelArray addObject:model];
                
            }
            
        }
        [rr close];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];

        });
        
      }
       //没有网络
    } else {
        [self addHint];
    }
    
    // 上拉加载
    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        if ([[NetWorkState shareInstance]reachability]) {
            [self loadMore];

        } else {
           
            [self addHint];
        }

        
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _modelArray.count;
}


// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MusicDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    
    [cell.moreButton addTarget:self action:@selector(moreButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
    musicRunModel *model = self.modelArray[indexPath.row];
   
// –––––––––––––––––––––––––––––– 数据库找 是否收藏过
    NSFetchRequest * request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];
    
    NSPredicate * cate = [NSPredicate predicateWithFormat:@"isCollection= '1'"];
    
    [request setPredicate:cate];
    
    NSArray * array = [_context executeFetchRequest:request error:nil];
    
    for (Entity * c  in array) {
        if ( [c.name isEqualToString:model.name]) {
            model.isCollection = YES;
            [cell.moreButton setBackgroundImage:[UIImage imageNamed:@"fillstar"] forState:UIControlStateNormal];
        }
}
// ––––––––––––––––––––––––––––––
    

    [cell cellFormodel:model];
    
    cell.selectionStyle  = UITableViewCellSelectionStyleNone;
    

    if (model.isChoose) {
        
        cell.chooseView.hidden = NO;
    }
    else
    {
        cell.chooseView.hidden = YES;
    }

    
    if (model.isCollection) {
        
        [cell.moreButton  setBackgroundImage:[UIImage imageNamed:@"fillstar"] forState:UIControlStateNormal];
    }
    else
    {
        [cell.moreButton  setBackgroundImage:[UIImage imageNamed:@"greenstar"] forState:UIControlStateNormal];
        
    }
    
    
    return cell;
    
}
// 添加收藏
- (void)moreButton:(UIButton *)button
{
   
    BOOL ishave = NO;
    
    MusicDetailTableViewCell * cell = (MusicDetailTableViewCell *)button.superview.superview;
    NSIndexPath * indexpath = [self.tableView indexPathForCell:cell];
    musicRunModel * model  = _modelArray[indexpath.row];
    

    
    NSFetchRequest * request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];
    
    NSPredicate * cate = [NSPredicate predicateWithFormat:@"isCollection= '1'"];
    
    [request setPredicate:cate];
    
    
    // 点击按钮的时候 搜索数据库 isCollection
    
    // 判断是否存在 同样的model  存在就不添加  并且删除
    
    NSArray * array = [_context executeFetchRequest:request error:nil];
    
    for (Entity * c  in array) {
        if ( [c.name isEqualToString:model.name]) {
            ishave = YES;
            model.isCollection = NO;
        [button  setBackgroundImage:[UIImage imageNamed:@"greenstar"] forState:UIControlStateNormal];
            [_context deleteObject:c];
            [_context save:nil];
        }
    }
    
    if (!ishave) {
        Entity  * c = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:_context];
        model.isCollection = YES;
        
       // [button setTitle:@"❤️" forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"fillstar"] forState:UIControlStateNormal];
        
        c.name = model.name;
        c.albumUrl = model.albumUrl;
        c.author = model.author;
        c.introduce = model.introduce;
        c.url = model.url;
        c.tableName = model.tableName;
        c.bpm = [NSNumber numberWithInteger:model.bpm];
        c.isCollection = [NSNumber numberWithBool:YES];
        [_context save:nil];
        
    }
   
      [self.tableView reloadData];
    
  

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    for (MusicDetailTableViewCell * cell in self.tableView.visibleCells) {
        cell.chooseView.hidden = YES;
    }
    for (musicRunModel *model in self.modelArray) {
        model.isChoose = NO;
    }
    

    
       MusicPlayViewController * play = [[MusicPlayViewController alloc]initWithNibName:@"musicPlay" bundle:[NSBundle mainBundle]];
       musicRunModel * model = self.modelArray[indexPath.row];
    
       play.model = model;
       
       play.modelArray = _modelArray;
       
       play.index = indexPath.row;
    
    // -------------------------------- 显示谁被选中的歌曲
    model.isChoose = YES;
    
    MusicDetailTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    cell.chooseView.hidden = NO;
    
    
    [self presentViewController:play animated:YES completion:nil];

}


- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(modalViewControllerDidClickedDismissButton:)]) {
        [self.delegate modalViewControllerDidClickedDismissButton:self];
    }
}


#pragma mark ---- 没有网络的提示框 ----
- (void)addHint
{
    // 没有网络的提示框
    _hint = [[UIView alloc]initWithFrame:CGRectMake(KWIDTH / 4, KHEIGHT / 2 - KHEIGHT / 15, KWIDTH / 2, KHEIGHT / 15 * 2)];
    _hint.backgroundColor = [UIColor blackColor];
    _hint.alpha = 0.7;
    _hint.layer.cornerRadius = 10;
    [self.view addSubview:_hint];
    
    UIImageView *noNetworkimageView = [[UIImageView alloc]initWithFrame:CGRectMake(_hint.frame.size.width / 3 + 3, 0, _hint.frame.size.width / 3 + 3, _hint.frame.size.width / 3 * 53 / 63)];
    noNetworkimageView.image = [UIImage imageNamed:@"noNetwork"];
    [_hint addSubview:noNetworkimageView];
    
    UILabel *hintLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, _hint.frame.size.height / 2, KWIDTH / 2, _hint.frame.size.height / 2)];
    hintLabel.text = @"网络超时";
    hintLabel.textAlignment = NSTextAlignmentCenter;
    hintLabel.textColor = [UIColor whiteColor];
    [_hint addSubview:hintLabel];
    
    [self performSelector:@selector(removeHint) withObject:nil afterDelay:3];
    
}

- (void)removeHint
{
    [_hint removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
